﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace sqxt
{
    public partial class addr : Form
    {
        public addr()
        {
            InitializeComponent();
        }
        public addr(bool b)
        {
            dj = b;
            InitializeComponent();
        }
        bool dj=false;
        SqlConnection conn = new SqlConnection(Dbconnect.s1);
        DataTable dt;
        SqlDataAdapter sda;
        string s1 = "block_id", s2 = "parent_id", s3 = "block_name", s4 = "";
        private void addr_Load(object sender, EventArgs e)
        {
           //把数据库的居委表的数据全部读出来，显示为树形
            try
            {
               
                TreeNodeCollection treeNodeCollection=treeView1.Nodes;
                sda = new SqlDataAdapter("select block_id,parent_id,block_name,rootNodeTag  from block", Dbconnect.s1);
                dt = new DataTable();
                dt.TableName = "block";
                sda.Fill(dt);
                dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };
                InitTree(dt, s1, s2, s3, treeNodeCollection, s4);
            }
            catch (Exception e1)
            {
                
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }


        }



        public static void InitTree(DataTable dt, string nodeID, string parentID, string nodeName, TreeNodeCollection treeNodeCollection, string rootNodeTag)
        {
            try
            {
                TreeNode tmpNode;
                DataView dv = new DataView();
                dv.Table = dt;
                if (rootNodeTag != "" || rootNodeTag != null)
                    dv.RowFilter = parentID + "='" + rootNodeTag + "'";//dataview中选一行
                foreach (DataRowView drv in dv)//循环，把地址读出来
                {
                    tmpNode = new TreeNode();
                    tmpNode.Text = drv[nodeName].ToString();//节点名字
                    tmpNode.Tag = drv[nodeID];//节点id
                    string father = drv[nodeID].ToString();
                    treeNodeCollection.Add(tmpNode);
                    InitTree(dt, nodeID, parentID, nodeName, tmpNode.Nodes, father);
                }
            }
            catch (Exception te)
            {
                MessageBox.Show(te.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void 添加下级地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //1.当一个节点有对应链接资料时，不可以增加子节点   
                //2.当一个节点有对应链接资料时，可以增加图片   

                TreeNode treeNode = new TreeNode("新节点");
                treeNode.Tag = MaxRecordNumber(dt, "block_id") + 1;
                treeView1.SelectedNode.Nodes.Add(treeNode);
                AddDeleteNode(treeNode, treeView1.SelectedNode.Tag.ToString(), "Add");
                treeView1.SelectedNode = treeNode;
                //LoadTreeView.LoadTreeNodeImage(treeView.SelectedNode, this.imageList1, NodeImageMode);
                //执行指定节点的选定操作   
                //this.treeViewAfterSelect(treeView.SelectedNode);
                menuItemRename_Click(new object(), new System.EventArgs());
                SqlCommandBuilder scb = new SqlCommandBuilder(sda);
                sda.Update(dt);
            }
            catch (Exception te)
            {
                MessageBox.Show(this, te.Message, "ErrorChild", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }   

        }

        private void 删除地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show(this, "删除节点《" + treeView1.SelectedNode.Text.Trim() + "》，与其对应的信息也将被删除，你确定要删除吗？", "Information", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    //判断选定的节点是否存在下一级节点   
                    if (treeView1.SelectedNode.Nodes.Count == 0)
                    {
                        //删除节点   
                        TreeNode deleNode = treeView1.SelectedNode;
                        string strSql = "delete   from   block   where   block_id ='" + deleNode.Tag + "'";
                        treeView1.Nodes.Remove(deleNode);
                        conn.Open();
                        SqlCommand da = new SqlCommand(strSql, conn);
                        da.ExecuteNonQuery();
                        conn.Close();
                    }
                    else
                        MessageBox.Show("请先删除此节点中的子节点！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception te)
            {
                MessageBox.Show(this, te.Message, "ErrorDelete", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
            }

        }
        bool rework = false;
        int i;
        private void 修改地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            TreeNode mySelectedNode = treeView1.SelectedNode;
            if (mySelectedNode != null)
            {
                rework = true;
                i = Convert.ToInt32(mySelectedNode.Tag);
                treeView1.SelectedNode = mySelectedNode;
                treeView1.LabelEdit = true;
                mySelectedNode.BeginEdit();
            }
            else
                MessageBox.Show("No   tree   node   selected   .\n", "Invalid   selection");
        }

        ///   <summary>   
        ///   返回指定表的最大NodeID号码，也就是当前选定节点的tag   
        ///   </summary>   
        ///   <param   name="dt">数据表</param>   
        ///   <param   name="columnName">数据列</param>   
        ///   <returns>最大NodeID号码</returns>   
        private int MaxRecordNumber(DataTable dt, string columnName)
        {
            int number = 0;
            DataView dv = dt.DefaultView;
            dv.Sort = columnName + "   ASC";//一个字符串，它包含列名，后跟“ASC”（升序）或“DESC”（降序）。在默认情况下，列按升序排列。多个列可用逗号隔开。   
            foreach (DataRow dr in dt.Rows)
            {
                number = Convert.ToInt16(dr[columnName].ToString().Trim()) > number ? Convert.ToInt16(dr[columnName].ToString().Trim()) : number;
            }
            return number;
        }


        //节点重命名
        private void menuItemRename_Click(object sender, System.EventArgs e)
        {
            TreeNode mySelectedNode = treeView1.SelectedNode;
            if (mySelectedNode != null)
            {
                treeView1.SelectedNode = mySelectedNode;
                treeView1.LabelEdit = true;
                mySelectedNode.BeginEdit();
            }
            else
                MessageBox.Show("No   tree   node   selected   .\n", "Invalid   selection");
        }   




        ///   <summary>   
        ///   在数据表中增加节点或删除节点   
        ///   </summary>   
        ///   <param   name="addDeleteNode">要增加或删除的节点</param>   
        ///   <param   name="parentNodeId">要增加或删除节点的父节点</param>   
        ///   <param   name="AddDeleteTag">增删节点标志（add为增加节点，delete为删除节点，不区分大小写）</param>   
        private void AddDeleteNode(TreeNode addDeleteNode, string parentNodeId, string AddDeleteTag)
        {
            try
            {
                if (AddDeleteTag.ToUpper() == "ADD")
                {
                    object key = parentNodeId;
                    DataRow dr = dt.Rows.Find(key);
                    DataRow drNew = dt.NewRow();
                    if (dr != null)
                    {
                        drNew["Parent_ID"] = dr["block_id"];
                    }
                    else
                    {
                        drNew["Parent_ID"] = s4;
                    }
                    drNew["block_id"] = (int)addDeleteNode.Tag;
                    drNew["block_name"] = addDeleteNode.Text.Trim();
                    dt.Rows.Add(drNew);
                }
                else
                {
                    if (AddDeleteTag.ToUpper() == "DELETE")
                    {
                        dt.Rows[treeView1.SelectedNode.Level].Delete();
                    }
                }
               
            }
            catch (Exception te)
            {
                MessageBox.Show(this, te.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void 添加根地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                TreeNode treeNode = new TreeNode("新节点");
                menuItemRename_Click(new object(), new System.EventArgs());
                treeNode.Tag = MaxRecordNumber(dt, "block_id") + 1;
                this.treeView1.Nodes.Add(treeNode);
                AddDeleteNode(treeNode, s4, "Add");
                treeView1.SelectedNode = treeNode;
               // LoadTreeView.LoadTreeNodeImage(treeView.SelectedNode, this.imageList1, NodeImageMode);
                //执行指定节点的选定操作   
                //this.treeViewAfterSelect(treeView.SelectedNode);
               
                SqlCommandBuilder scb = new SqlCommandBuilder(sda);
                sda.Update(dt);
            }
            catch (Exception te)
            {
                MessageBox.Show(this, te.Message, "ErrorRoot", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }



        private void 添加同级地址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //判断是否选定组件中的根节点   
                if (treeView1.SelectedNode.Parent == null)
                {
                    MessageBox.Show("节点<" + treeView1.SelectedNode.Text.Trim() + ">为根节点，要加入兄弟节点，请使用\"加入根节点\"选项！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                TreeNode treeNode = new TreeNode("新节点");
                treeNode.Tag = MaxRecordNumber(dt, "block_id") + 1;
                treeView1.SelectedNode.Parent.Nodes.Add(treeNode);
                AddDeleteNode(treeNode, treeView1.SelectedNode.Parent.Tag.ToString().Trim(), "Add");
                treeView1.SelectedNode = treeNode;
                //执行指定节点的选定操作   
                menuItemRename_Click(new object(), new System.EventArgs());
            }
            catch (Exception te)
            {
                MessageBox.Show(this, te.Message, "ErrorParent", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }   

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

          
                TreeNode deleNode = treeView1.SelectedNode;
                string strSql = "update  block set block_name='"+deleNode.Text.ToString()+"'  where   block_id ='" + deleNode.Tag + "'";
                conn.Open();
                SqlCommand da = new SqlCommand(strSql, conn);
                da.ExecuteNonQuery();
                conn.Close();

            


        }

        private void toolStripButton1_Click(object sender, EventArgs e)//保存
        {
            //if (rework)
            //{
                TreeNode deleNode = treeView1.SelectedNode;
                string strSql = "update  block set block_name='" + deleNode.Text.ToString() + "'  where   block_id ='" + deleNode.Tag + "'";
                conn.Open();
                SqlCommand da = new SqlCommand(strSql, conn);
                da.ExecuteNonQuery();
                conn.Close();

            //}
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            删除地址ToolStripMenuItem_Click(sender,e);
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            修改地址ToolStripMenuItem_Click(sender,e);
        }
        TreeNode pnode; string add="";
      private   string selectParentNode(TreeNode   node)   //递归遍历子树的上级节点
       {
           
            if(node.Parent   is   TreeNode)   
            {   
               pnode=(TreeNode)node.Parent;
               
                  
                   add = pnode.Text.ToString() + add;
                   selectParentNode(pnode);
               
                
            }
            return add;
      }

        public string dizhi = "";
        private void treeView1_DoubleClick(object sender, EventArgs e)//双击事件
        {
            if (dj)
            {
                TreeNode trnode = treeView1.SelectedNode;
                dizhi = selectParentNode(trnode) + trnode.Text.ToString();
                ResidentAdd f = (ResidentAdd)this.Owner;
                f.textBoxX2.Text = dizhi;
                this.Close();
            }
        }

        }

}